<template>
  <Drawer>
    <BaseForm />
  </Drawer>
</template>
<script lang="tsx" setup>
import type { MenuInfoPlain } from '#/api/sys/model/menuModel';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import { createRole, getRoleDetail, updateRole } from '#/api/sys/role';
// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
// 定义表单
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false, // 不显示操作按钮
  layout: 'vertical',
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      label: $t('sys.role.roleName'),
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        clearable: true,
      },
      fieldName: 'sort',
      label: $t('sys.role.sort'),
      rules: 'required',
    },
    // {
    //   component: 'Input',
    //   fieldName: 'code',
    //   label: $t('sys.role.roleValue'),
    //   rules: 'required',
    // },
    {
      component: 'Input',
      // 对应组件的参数
      fieldName: 'defaultRouter',
      label: $t('sys.role.defaultRouter'),
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      defaultValue: '1',
      componentProps: {
        isButton: true,
        options: [
          {
            label: $t('sys.role.start'),
            value: '1',
          },
          {
            label: $t('sys.role.stop'),
            value: '0',
          },
        ],
      },
      fieldName: 'status',
      label: $t('sys.role.status'),
    },
    {
      component: 'Input',
      fieldName: 'remark',
      componentProps: {
        type: 'textarea',
        rows: 4,
        maxlength: 200,
        showWordLimit: true,
      },
      label: $t('sys.role.remark'),
    },
  ],
});

// 定义弹窗
const [Drawer, drawerApi] = useVbenDrawer({
  // 表单校验
  async onConfirm() {
    // 提交表单
    const { type, id } = drawerApi.getData<Record<string, any>>();
    const isPass = await baseFormApi.validateAndSubmitForm(); // 校验表单
    if (!isPass) {
      return; // 校验不通过
    }
    if (type === 'addData') {
      addOrUpdateRole(isPass);
    }
    if (type === 'editData') {
      addOrUpdateRole(isPass, id);
    }
  },
  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 设置默认值
      const { type, id } = drawerApi.getData<Record<string, any>>();
      // 新增打开弹窗时重置表单
      if (type === 'addData') {
        baseFormApi.resetForm();
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        await getRoleDetail(id).then((res: any) => {
          baseFormApi.setValues({
            ...res,
            status: String(res.status),
          });
          // 关闭加载中状态
        });
      }
    }
  },
});

/**
 * @author Buke
 * @description 新增或编辑职位
 * @param {MenuInfoPlain} formData - 表单数据对象
 * @param {number} [id] - 职位ID（存在表示编辑，不存在表示新增）
 * @returns {void}
 * @todo 新增倒序排序
 */
async function addOrUpdateRole(
  formData: MenuInfoPlain,
  id?: number,
): Promise<void> {
  const data = {
    ...formData,
    id,
    sort: Number(formData.sort),
    status: Number(formData.status),
  };
  id ? await updateRole(data) : await createRole(data);
  ElMessage.success($t('common.operateSuccess'));
  emit('refresh');
}
</script>
